package work.soho.proxy;

import work.soho.proxy.aliyun.parts.PartsManage;
import work.soho.proxy.ui.ConfigureFrame;
import work.soho.proxy.ui.SystemTrayUi;
import work.soho.proxy.ui.TrayIconUi;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.URL;

public class ProxyApplication {
    public static ConfigManage configManage;
    public static ProxyDaemon proxyDaemon;
    public static SystemTrayUi minIcon;

    /**
     * 切换图标
     *
     * @param colour
     */
    public static void switchIcon(String colour) {
        if(colour == null) {
            colour = "yellow";
        }
        URL uri = Thread.currentThread().getContextClassLoader().getResource("images/"+colour+"-proxy-icon.png");
      //  minIcon.setImage(Toolkit.getDefaultToolkit().getImage(uri));
        minIcon.setImage(uri);
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        configManage = new ConfigManage();
        PartsManage.setConfig(configManage.getPartsConfigure());
        proxyDaemon = new ProxyDaemon();
        proxyDaemon.setConfigManage(configManage);
        //检查配置文件是否存在
        do {
            if(configManage.isExists()) {
                break;
            } else {
                ConfigureFrame.instance().show();
            }
            synchronized (ConfigureFrame.instance().getFrame()) {
                ConfigureFrame.instance().getFrame().wait();
            }

            configManage.reloadPartsConfigure();
        } while (true);

        //启动托盘程序
        URL uri = Thread.currentThread().getContextClassLoader().getResource("images/yellow-proxy-icon.png");
        Image image = Toolkit.getDefaultToolkit().getImage(uri);
        minIcon = new SystemTrayUi(uri);
        //默认程序启动代理
        if(ProxyApplication.configManage.isExists()) {
            try {
                ProxyApplication.proxyDaemon.check();
            } catch (Exception checkE) {
                checkE.printStackTrace();
            }
        } else {
            //弹窗配置配置信息
            ConfigureFrame.instance().show();
        }
    }

    /**
     * 弹出提示消息
     *
     * @param infoMessage
     * @param headerMessage
     */
    public static void infoBox(String infoMessage, String headerMessage)
    {
        JOptionPane.showMessageDialog(null, infoMessage,
                headerMessage, JOptionPane.CLOSED_OPTION);
    }
}
